<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace backend\controllers;

use Yii;
use yii\web\AdminController;

class DevelopController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'develop';

    /****************** 产品start ******************/
    //研发产品列表
    public function actionIndex()
    {
        $sql = 'select * from develop_product_category';
        $category = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        return $this->render('product-master', ['category' => $category]);
    }

    //产品分类列表数据
    public function actionProductList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select pm.*,pc.name categoryName from develop_product_master pm
                     left join develop_product_category pc on pm.developProductCategoryId=pc.AutoId WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT from develop_product_master pm WHERE 1=1 ';

        if (isset($data['productName']) && !empty($data['productName'])) {
            $sql .= ' AND pm.name like "%' . $data['productName'] . '%"';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY pm.AutoId desc';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //产品分类详情
    public function actionProductDtl()
    {
        $data = Yii::$app->request->post();
        $sql = 'select * from develop_product_master WHERE AutoId ='.$data['id'];
        $category = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('操作成功', 200, $category);
    }

    //修改、编辑产品分类
    public function actionAddProduct()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['code'] = $data['product_code'];
        $model['name'] = $data['product_name'];
        $model['developProductCategoryId'] = $data['product_category'];
        $model['sort'] = $data['product_sort'];
        $model['useflg'] = $data['product_useflg'];

        try {
            if (empty($data['id'])) {
                $ckSql = "select count(0) cnt from develop_product_master where name='" . $model['name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('产品名称已存在', 500);
                }
                $model['creator'] = $this->getCreator();
                $model['createtime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->insert('develop_product_master', $model)->execute();

            } else {
                $categoryId = $data['id'];
                $ckSql = "select count(0) cnt from develop_product_master where AutoId<>" . $categoryId . " and name='" . $model['name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('产品名称已存在', 500);
                }
                $model['updator'] = $this->getCreator();
                $model['updatetime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->update('develop_product_master', $model, ['AutoId' => $categoryId])->execute();
            }
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }
    /****************** 产品end ******************/



    /****************** 产品分类start ******************/
    //产品分类列表
    public function actionProductCategory()
    {
        return $this->render('product-category');
    }

    //产品分类列表数据
    public function actionProductCategoryList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select * from develop_product_category WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT from develop_product_category WHERE 1=1 ';

        if (isset($data['categoryName']) && !empty($data['categoryName'])) {
            $sql .= ' AND name like "%' . $data['categoryName'] . '%"';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY AutoId desc';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //产品分类详情
    public function actionProductCategoryDtl()
    {
        $data = Yii::$app->request->post();
        $sql = 'select * from develop_product_category WHERE AutoId ='.$data['id'];
        $category = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('操作成功', 200, $category);
    }

    //修改、编辑产品分类
    public function actionAddProductCategory()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['code'] = $data['category_code'];
        $model['name'] = $data['category_name'];
        $model['sort'] = $data['category_sort'];
        $model['useflg'] = $data['category_useflg'];

        try {
            if (empty($data['id'])) {
                $ckSql = "select count(0) cnt from develop_product_category where name='" . $data['category_name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('分类名称已存在', 500);
                }
                $model['creator'] = $this->getCreator();
                $model['createtime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->insert('develop_product_category', $model)->execute();

            } else {
                $categoryId = $data['id'];
                $ckSql = "select count(0) cnt from develop_product_category where AutoId<>" . $categoryId . " and name='" . $data['category_name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('分类名称已存在', 500);
                }
                $model['updator'] = $this->getCreator();
                $model['updatetime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->update('develop_product_category', $model, ['AutoId' => $categoryId])->execute();
            }
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }
    /****************** 产品分类end ******************/



    /****************** BOM start ******************/
    //产品分类列表
    public function actionBom()
    {
        return $this->render('bom-master');
    }

    //产品分类列表数据
    public function actionBomList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select bm.*,pm.name as productName from develop_bom_master bm inner join develop_product_master pm on bm.developProductId=pm.AutoId WHERE 1=1 ';
        $sql_count = 'select COUNT(0) CNT from develop_bom_master bm inner join develop_product_master pm on bm.developProductId=pm.AutoId WHERE 1=1 ';

        if (isset($data['bomName']) && !empty($data['bomName'])) {
            $sql .= ' AND bm.name like "%' . $data['bomName'] . '%"';
        }
        if (isset($data['productName']) && !empty($data['productName'])) {
            $sql .= ' AND pm.name like "%' . $data['productName'] . '%"';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY bm.AutoId desc';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //产品分类详情
    public function actionBomDtl()
    {
        $bom = array();
        $data = Yii::$app->request->get();
        if(isset($data['id']) && !empty($data['id'])){
            $sql = 'select * from develop_bom_master WHERE AutoId ='.$data['id'];
            $bom = Yii::$app->db_assemble->createCommand($sql)->queryOne();

            $sql = 'select bd.*,mm.code,mm.name,mm.minUnit,mm.useUnit,mm.referPrice,mc.name as categoryName from develop_bom_detail bd
                    inner join develop_materiel_master mm on bd.developMaterielId=mm.AutoId
                    inner join develop_materiel_category mc on mm.developMaterielCategoryId=mc.AutoId where bd.developBomId = '.$data['id'];
            $bom['dtl'] = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        }

        $sql = 'select * from develop_product_master';
        $product = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        return $this->render('bom-detail', ['product' => $product, 'bom' => $bom]);
    }

    //修改、编辑产品分类
    public function actionAddBom()
    {
        $data = Yii::$app->request->post();
        $model = array();
        $model['code'] = $data['bom_code'];
        $model['name'] = $data['bom_name'];
        $model['developProductId'] = $data['bom_product'];
        $model['version'] = $data['version'];
        $model['remark'] = $data['remark'];

        $currentDate = date('Y-m-d H:i:s');
        $bomId = (isset($data['bom_Id']) && !empty($data['bom_Id'])) ? $data['bom_Id'] : '';
        $ckSql = "select count(0) cnt from develop_bom_master where name='" . $model['name'] . "'";
        if ($bomId) $ckSql .= " and AutoId<>" . $bomId;
        $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
        if ($ck_count && $ck_count['cnt']) {
            $this->retJson('bom名称已存在', 500);
        }

        $transaction = Yii::$app->db_assemble->beginTransaction();
        try {
            if ($bomId) {
                $model['updator'] = $this->getCreator();
                $model['updateTime'] = $currentDate;
                Yii::$app->db_assemble->createCommand()->update('develop_bom_master', $model, ['AutoId' => $bomId])->execute();
                $delSql = "DELETE FROM develop_bom_detail WHERE developBomId='" . $bomId . "'";
                Yii::$app->db_assemble->createCommand($delSql)->execute();
            } else {
                $model['useFlg'] = 1;
                $model['creator'] = $this->getCreator();
                $model['createTime'] = $currentDate;
                Yii::$app->db_assemble->createCommand()->insert('develop_bom_master', $model)->execute();
                $bomId = Yii::$app->db_assemble->getLastInsertId();
            }

            foreach ($data['materiels'] as $ma) {
                $bomDtl = array(
                    'creator' => $this->getCreator(),
                    'createTime' => $currentDate,
                    'developBomId' => $bomId,
                    'developMaterielId' => $ma['materielId'],
                    'useQty' => $ma['useQty'],
                    'tolerance_min' => $ma['tolerance_min'],
                    'tolerance_max' => $ma['tolerance_max'],
                    'type' => $ma['type'],
                    'useFlg' => $ma['useFlg'],
                );
                Yii::$app->db_assemble->createCommand()->insert('develop_bom_detail', $bomDtl)->execute();
            }

            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

    //启用、禁用
    public function actionChangeStatus(){
        $data = Yii::$app->request->post();
        $model = array(
            'useFlg' => $data['status']
        );
        Yii::$app->db_assemble->createCommand()->update('develop_bom_master', $model, ['AutoId' => $data['id']])->execute();
        $this->retJson('操作成功', 200);
    }
    /****************** BOM end ******************/


    /****************** 物料分类start ******************/
    //产品分类列表
    public function actionMaterielCategory()
    {
        return $this->render('materiel-category');
    }

    //产品分类列表数据
    public function actionMaterielCategoryList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select * from develop_materiel_category WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT from develop_materiel_category WHERE 1=1 ';

        if (isset($data['categoryName']) && !empty($data['categoryName'])) {
            $sql .= ' AND name like "%' . $data['categoryName'] . '%"';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY AutoId desc';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //产品分类详情
    public function actionMaterielCategoryDtl()
    {
        $data = Yii::$app->request->post();
        $sql = 'select * from develop_materiel_category WHERE AutoId ='.$data['id'];
        $category = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('操作成功', 200, $category);
    }

    //修改、编辑产品分类
    public function actionAddMaterielCategory()
    {
        $data = Yii::$app->request->post();

        $model = array();
        $model['code'] = $data['category_code'];
        $model['name'] = $data['category_name'];
        $model['sort'] = $data['category_sort'];
        $model['useFlg'] = $data['category_useflg'];

        try {
            if (empty($data['id'])) {
                $ckSql = "select count(0) cnt from develop_materiel_category where name='" . $data['category_name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('分类名称已存在', 500);
                }
                $model['creator'] = $this->getCreator();
                $model['createtime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->insert('develop_materiel_category', $model)->execute();

            } else {
                $categoryId = $data['id'];
                $ckSql = "select count(0) cnt from develop_materiel_category where AutoId<>" . $categoryId . " and name='" . $data['category_name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('分类名称已存在', 500);
                }
                $model['updator'] = $this->getCreator();
                $model['updatetime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->update('develop_materiel_category', $model, ['AutoId' => $categoryId])->execute();
            }
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }
    /****************** 物料分类end ******************/


    /****************** 物料start ******************/
    //研发产品列表
    public function actionMateriel()
    {
        $sql = 'select * from develop_materiel_category';
        $category = Yii::$app->db_assemble->createCommand($sql)->queryAll();
        return $this->render('materiel-master', ['category' => $category]);
    }

    //产品分类列表数据
    public function actionMaterielList()
    {
        $data = Yii::$app->request->post();
        $sql = '';
        $sql_list = 'select mm.*,mc.name categoryName from develop_materiel_master mm
                     left join develop_materiel_category mc on mm.developMaterielCategoryId=mc.AutoId WHERE 1=1 ';
        $sql_count = 'SELECT COUNT(0) CNT from develop_materiel_master mm WHERE 1=1 ';

        if (isset($data['materielName']) && !empty($data['materielName'])) {
            $sql .= ' AND mm.name like "%' . $data['materielName'] . '%"';
        }

        if (isset($data['searchKey']) && !empty($data['searchKey'])) {
            $sql .= ' AND (mm.name like "%' . $data['searchKey'] . '%" or mm.code like "%' . $data['searchKey'] . '%")';
        }

        $list_count = Yii::$app->db_assemble->createCommand($sql_count . $sql)->queryOne();
        $count = $list_count['CNT'];
        $sql .= ' ORDER BY mm.AutoId desc';
        if ($data['start'] || $data['length']) {
            $sql .= ' limit ' . $data['start'] . ',' . $data['length'];
        }

        $list = Yii::$app->db_assemble->createCommand($sql_list . $sql)->queryAll();
        if (empty($list)) {
            $list = array();
        }

        //相关参数 http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    //产品分类详情
    public function actionMaterielDtl()
    {
        $data = Yii::$app->request->post();
        $sql = 'select * from develop_materiel_master WHERE AutoId ='.$data['id'];
        $materiel = Yii::$app->db_assemble->createCommand($sql)->queryOne();
        $this->retJson('操作成功', 200, $materiel);
    }

    //修改、编辑产品分类
    public function actionAddMateriel()
    {
        $data = Yii::$app->request->post();
        $model = array();
        $model['code'] = $data['materiel_code'];
        $model['name'] = $data['materiel_name'];
        $model['developMaterielCategoryId'] = $data['materiel_category'];
        $model['minUnit'] = $data['minUnit'];
        $model['useUnit'] = $data['useUnit'];
        $model['referPrice'] = $data['referPrice'];
        $model['useFlg'] = $data['useFlg'];
        $model['img'] = (isset($data['img'])&&is_array($data['img'])) ? implode(',', $data['img']) : '';

        try {
            if (empty($data['id'])) {
                $ckSql = "select count(0) cnt from develop_materiel_master where name='" . $model['name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('物料名称已存在', 500);
                }
                $model['creator'] = $this->getCreator();
                $model['createtime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->insert('develop_materiel_master', $model)->execute();

            } else {
                $categoryId = $data['id'];
                $ckSql = "select count(0) cnt from develop_materiel_master where AutoId<>" . $categoryId . " and name='" . $model['name'] . "'";
                $ck_count = Yii::$app->db_assemble->createCommand($ckSql)->queryOne();
                if ($ck_count && $ck_count['cnt']) {
                    $this->retJson('物料名称已存在', 500);
                }
                $model['updator'] = $this->getCreator();
                $model['updatetime'] = date('Y-m-d H:i:s');
                Yii::$app->db_assemble->createCommand()->update('develop_materiel_master', $model, ['AutoId' => $categoryId])->execute();
            }
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }
    /****************** 物料end ******************/


    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }

    //图片上传
    public function actionImgUpload()
    {
        if($_FILES['uploadFile']['error']){
            $this->retJson('上传失败', 500);
        }
        $time = time();
        $file = $_FILES['uploadFile'];
        $tmp_name = $file['tmp_name'];
        $type = $file['type'];
        $type = explode('/', $type);
        $type = $type[1];
        $path = Yii::$app->params['SUPPLIER_UPLOAD_PATH'];
        $dir = 'materiel/' . date('Ymd') . '/';
        $fileName = $time . '.' . $type;

        if (!file_exists($path . $dir)) {   //判断该目录是否存在
            mkdir($path . $dir, 0777, true);
        }
        move_uploaded_file($tmp_name, $path . $dir . $fileName);
        $fileRes = array(
            'key' => $time,
            'src' => '/images/' . $dir . $fileName,
            'url' => $dir . $fileName
        );
        $this->retJson('操作成功', 200, $fileRes);
    }
}